// 提供统一方法入口
export default {
  postRequest(url, data, auth) {
    return postRequest(url, data, auth);
  },
  getRequest(url, auth) {
    return getRequest(url, auth);
  },
};

export async function getHandler(url=""){
  return handleRequest("GET",url)
}

export async function postHandler(url="",data = {}){
  return handleRequest("POST",url,data)
}

// 处理请求
export async function handleRequest(method = "",url = "",data = {}) {
  try {
    let resJson = {};
    if (method == "post") {
      resJson = await postRequest(url, data);
    } else {
      resJson = await getRequest(url);
    }

    if (resJson) {
      return resJson;
    } else {
      throw new Error(resJson.message);
    }
  } catch (error) {
    throw new Error(error.message);
  }
}

const token = 'sk-3fa79c45a7f9467781c387f5c7c5c5b9';

// post
export async function postRequest(url = "", data = {}, auth = true) {
  const options = {
    method: "POST",
    headers: {
      "Access-Control-Allow-Origin":"*",
      "Content-Type": "application/json",
      "X-DashScope-Async": "enable",
    },
    body: JSON.stringify(data),
  };

  // 如果 auth 参数为 true，则添加 token 到请求头中
  if (auth) {
    options.headers.Authorization = `Bearer ${token}`;
  }

  try {
    const baseUrl = "https://dashscope.aliyuncs.com/api/v1";
    console.log("接口访问url：", baseUrl+url, "，参数：", options);
    const response = await fetch(baseUrl+url, options);
    const resJson = await response.json();
    console.log("接口访问结果：", resJson);
    return resJson;
  } catch (error) {
    console.error("请求错误:", error);
    throw new error(error.message);
  }
}

export async function getRequest(url = "", auth = true) {
  const options = {
    method: "GET",
    headers: {
      "Access-Control-Allow-Origin":"*",
      "Content-Type": "application/json",
    },
  };

  // 如果 auth 参数为 true，则添加 token 到请求头中
  if (auth) {
    options.headers.Authorization = `Bearer ${token}`;
  }

  try {
    const baseUrl = "/proxy/api/v1";
    console.log("接口访问url：", baseUrl+url, "，参数：", options);
    const response = await fetch(baseUrl+url, options);
    const resJson = await response.json();
    console.log("接口访问结果：", resJson);
    return resJson;
  } catch (error) {
    console.error("请求错误:", error);
    throw error;
  }
}
